/*
 * WIN32.C
 *
 * Convert VT100/ANSI escape sequences into native Win32 API implementations.
 *
 * Copyright (c) 2015 Malcolm J. Smith
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "cvtvt.h"

#define DEFAULT_COLOR (7)

//
//  Win32 functions
//

BOOL
Win32InitializeStream(
    HANDLE hOutput,
    HANDLE hControl
    )
{
    return TRUE;
}

BOOL
Win32EndStream(
    HANDLE hOutput,
    HANDLE hControl
    )
{
    return TRUE;
}

BOOL
Win32ProcessAndOutputText(
    HANDLE hOutput,
    HANDLE hControl,
    LPSTR StringBuffer,
    ULONG BufferLength
    )
{
    ULONG  BytesTransferred;

    WriteFile(hOutput,StringBuffer,BufferLength,&BytesTransferred,NULL);
    return TRUE;
}

BOOL
Win32ProcessAndOutputEscape(
    HANDLE hOutput,
    HANDLE hControl,
    LPSTR StringBuffer,
    ULONG BufferLength
    )
{
    LPSTR CurrentPoint = StringBuffer;
    ULONG CurrentOffset = 0;
    WORD  NewColor = DEFAULT_COLOR;
    ULONG RemainingLength;

    RemainingLength = BufferLength;

    //
    //  We expect an escape initiator (two chars) and a 'm' for color
    //  formatting.  This should already be validated, the check here
    //  is redundant.
    //

    if (BufferLength >= 3 &&
        CurrentPoint[BufferLength - 1] == 'm') {

        DWORD code;
        BOOLEAN NewUnderline = FALSE;
        DWORD ColorTable[] = {0,
                              FOREGROUND_RED,
                              FOREGROUND_GREEN,
                              FOREGROUND_RED|FOREGROUND_GREEN,
                              FOREGROUND_BLUE,
                              FOREGROUND_BLUE|FOREGROUND_RED,
                              FOREGROUND_BLUE|FOREGROUND_GREEN,
                              FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED};

        CurrentPoint++;
        RemainingLength--;

        //
        //  For something manipulating colors, go through the semicolon
        //  delimited list and apply the changes to the current color
        //

        while (TRUE) {

            //
            //  Swallow either the ';' or '[' depending on whether we're
            //  at the start or an intermediate component
            //

            CurrentPoint++;
            RemainingLength--;

            code = memtoi(CurrentPoint, RemainingLength);
            if (code == 0) {
                NewColor = DEFAULT_COLOR;
                NewUnderline = FALSE;
            } else if (code == 1) {
                NewColor |= FOREGROUND_INTENSITY;
            } else if (code == 4) {
                NewUnderline = TRUE;
            } else if (code == 7) {
                NewColor = (WORD)(((NewColor & 0xf) << 4) | ((NewColor & 0xf0) >> 4));
            } else if (code == 39) {
                NewColor = (WORD)((NewColor & ~(0xf)) | (DEFAULT_COLOR & 0xf));
            } else if (code == 49) {
                NewColor = (WORD)((NewColor & ~(0xf0)) | (DEFAULT_COLOR & 0xf0));
            } else if (code >= 30 && code <= 37) {
                NewColor = (WORD)((NewColor & ~(0xf)) | ColorTable[code - 30]);
            } else if (code >= 40 && code <= 47) {
                NewColor = (WORD)((NewColor & ~(0xf0)) | (ColorTable[code - 40]<<4));
            } else if (code >= 90 && code <= 97) {
                NewColor = (WORD)((NewColor & ~(0xf)) | FOREGROUND_INTENSITY | ColorTable[code - 90]);
            } else if (code >= 100 && code <= 107) {
                NewColor = (WORD)((NewColor & ~(0xf0)) | BACKGROUND_INTENSITY | (ColorTable[code - 100]<<4));
            }

            //
            //  We expect this to end with an 'm' at the end of the string, or
            //  some other delimiter in the middle.  For paranoia maintain
            //  length checking.
            //

            CurrentOffset = memspn(CurrentPoint, RemainingLength, "0123456789");
            CurrentPoint += CurrentOffset;
            RemainingLength -= CurrentOffset;

            if (RemainingLength == 0 ||
                *CurrentPoint != ';') {

                break;
            }
        }

        if (NewUnderline) {
            NewColor |= COMMON_LVB_UNDERSCORE;
        }

        SetConsoleTextAttribute(hOutput, NewColor);
    } else if (hControl != INVALID_HANDLE_VALUE &&
               CurrentPoint[BufferLength - 1] == 't') {

        DWORD Operation;
        CONSOLE_SCREEN_BUFFER_INFO ScreenInfo;
        ULONG BytesTransferred;
        CHAR OutputString[32];

        Operation = memtoi(&CurrentPoint[2], RemainingLength - 2);

        if (Operation == 18) {
            if (GetConsoleScreenBufferInfo(hOutput, &ScreenInfo)) {
                sprintf(OutputString,
                        "%c[8;%i;%it",
                        27,
                        ScreenInfo.srWindow.Right - ScreenInfo.srWindow.Left + 1,
                        ScreenInfo.srWindow.Bottom - ScreenInfo.srWindow.Top + 1);

                WriteFile(hControl, OutputString, strlen(OutputString), &BytesTransferred, NULL);
            }
        }
    }
    return TRUE;
}

BOOL
Win32SetFunctions(
    PCALLBACK_FUNCTIONS CallbackFunctions
    )
{
    CallbackFunctions->InitializeStream = Win32InitializeStream;
    CallbackFunctions->EndStream = Win32EndStream;
    CallbackFunctions->ProcessAndOutputText = Win32ProcessAndOutputText;
    CallbackFunctions->ProcessAndOutputEscape = Win32ProcessAndOutputEscape;
    return TRUE;
}

// vim:sw=4:ts=4:et:
